package com.wkq.common.glide.disk;



import static com.wkq.common.AppProviderKt.CustomApplication;

import android.text.TextUtils;

import com.bumptech.glide.disklrucache.DiskLruCache;
import com.bumptech.glide.load.Key;
import com.bumptech.glide.load.engine.cache.DiskCache;
import com.bumptech.glide.load.engine.cache.SafeKeyGenerator;
import com.wkq.common.glide.GlideConstant;
import com.wkq.util.UriUtil;
import com.wkq.util.disk.DiskCacheManager;
import com.wkq.util.disk.SecretUtil;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: wkq
 * @Time: 2025/4/11 14:46
 * @Desc:
 */
public class VoiceDiskLruCacheWrapper implements DiskCache {

    private static final String TAG = "VoiceDiskLruCacheWrapper";

    private static final int APP_VERSION = 1;
    private static final int VALUE_COUNT = 1;
    private static VoiceDiskLruCacheWrapper wrapper;

    private final SafeKeyGenerator safeKeyGenerator;
    private final File directory;
    private final long maxSize;
    private final DiskCacheWriteLocker writeLocker = new DiskCacheWriteLocker();
    private DiskLruCache diskLruCache;


    @Deprecated
    public static synchronized DiskCache get(File directory, long maxSize) {

        if (wrapper == null) {
            wrapper = new VoiceDiskLruCacheWrapper(directory, maxSize);
        }
        return wrapper;
    }


    public static VoiceDiskLruCacheWrapper create(File directory, long maxSize) {
        return new VoiceDiskLruCacheWrapper(directory, maxSize);
    }


    protected VoiceDiskLruCacheWrapper(File directory, long maxSize) {
        this.directory = directory;
        this.maxSize = maxSize;
        this.safeKeyGenerator = new SafeKeyGenerator();
    }

    private synchronized DiskLruCache getDiskCache() throws IOException {
        if (diskLruCache == null) {
            diskLruCache = DiskLruCache.open(directory, APP_VERSION, VALUE_COUNT, maxSize);
        }
        return diskLruCache;
    }


    public String extractSourceKey(String key, String input) {
        if (input == null || input.isEmpty()) {
            return null;
        }
        // 定义正则表达式
        String regex = key + "=([^,]+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            // 提取匹配到的组
            return matcher.group(1);
        }
        return null;
    }


    @Override
    public File get(Key key) {

        File result = null;
        String safeKey = safeKeyGenerator.getSafeKey(key);
        try {
            final DiskLruCache.Value value = getDiskCache().get(safeKey);
            if (value != null) {
                result = value.getFile(0);
            }
            if (result==null||result.length()==0){
                String url = extractSourceKey("sourceKey", key.toString());
                String type = UriUtil.INSTANCE.extractSourceKey(GlideConstant.INSTANCE.getGlide_save_type_key(), key.toString());
                if (!TextUtils.isEmpty(type)) {
                    String mdfUrl = SecretUtil.getMD5Result(url);
                    String data = DiskCacheManager.getInstance(CustomApplication(),type).getFilePath(mdfUrl);
                    if (!TextUtils.isEmpty(data)) {
                        return new File(data);
                    }
                }
            }


        } catch (IOException e) {

        }



        return result;
    }

    @Override
    public void put(Key key, Writer writer) {

        String safeKey = safeKeyGenerator.getSafeKey(key);
        writeLocker.acquire(safeKey);
        try {
            try {

                DiskLruCache diskCache = getDiskCache();
                DiskLruCache.Value current = diskCache.get(safeKey);
                if (current != null) {
                    return;
                }

                DiskLruCache.Editor editor = diskCache.edit(safeKey);
                if (editor == null) {
                    throw new IllegalStateException("Had two simultaneous puts for: " + safeKey);
                }
                try {
                    File file = editor.getFile(0);
                    if (writer.write(file)) {
                        editor.commit();
                    }
                } finally {
                    editor.abortUnlessCommitted();
                }
            } catch (IOException e) {

            }
        } finally {
            writeLocker.release(safeKey);
        }
    }

    @Override
    public void delete(Key key) {
        String safeKey = safeKeyGenerator.getSafeKey(key);
        try {
            getDiskCache().remove(safeKey);
        } catch (IOException e) {

        }
    }

    @Override
    public synchronized void clear() {
        try {
            getDiskCache().delete();
        } catch (IOException e) {

        } finally {

            resetDiskCache();
        }
    }

    private synchronized void resetDiskCache() {
        diskLruCache = null;
    }
}